<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">

<head th:replace="fragments/common :: head" />

<body>
	<div th:replace="fragments/common :: bootstrap" />
	<div th:include="fragments/common :: admin (${isAdmin})" />

	<div th:if="${isAdmin}">
		<div class="portletBody">
			<div id="menu" th:include="fragments/menus :: main (new)" />
			<div class="page-header">
				<h1 th:text="#{site_synch.new_title}"></h1>
			</div>

			<div th:include="fragments/common :: error" />

			<form id="siteSynchForm" th:action="@{/save-siteSynchronization}" method="post">
				<div class="col-md-12 synchContainer">
					<div class="col-xl-5">
						<h3 th:text="#{site_synch.sakai_sites}">Sakai Sites</h3>
						<div class="card p-2 microsoft-block">
							<fieldset class="fieldset-collapse">
								<legend class="collapse-button" role="button" data-bs-toggle="collapse" data-bs-target=".fieldset-content"
									th:text="#{site_synch.filters}" tabindex="0"></legend>
								<div class="fieldset-content collapse show">
									<div th:replace="fragments/siteFilter :: siteFilter">
									</div>

									<div class="act">
										<input type="button" role='button' class="active" th:value="#{search}" onclick="filterSites(false)" />
										<input type='button' role='button' th:value="#{site_synch.filter.clear}" onclick="filterSites(true)" />
									</div>
								</div>
							</fieldset>

							<input id="site-search" type="text" class="form-control microsoft-search"
								onkeyup="searchFilter(this)"
								data-list="sites-list"
								th:placeholder="|&#xF002; #{search}|" />

							<div id="sakai-error"></div>
							<div>
								<ul id="sites-list" class="list-unstyled">
									<th:block th:fragment="sites(sitesList)">
										<th:block th:if="${sitesList != null and sitesList.size() > 0}">
											<li class="table-row" th:each="site : ${sitesList}">
												<label>
													<input type='checkbox' name="selectedSiteIds"
													th:value="${site.id}" />
													<span class="title-row" th:text="${site.title}"></span>
												</label>
											</li>
										</th:block>
										<li th:if="${sitesList == null}" th:text="#{site_synch.no_sites}"></li>
										<li th:if="${sitesList != null and sitesList.size() == 0}" th:text="#{site_synch.no_filtered_sites}"></li>
									</th:block>
								</ul>
							</div>
						</div>
					</div>

					<div class="col-xl-2 text-center">
						<div class="row arrow-container">
							<i class="fa fa-arrow-right"></i>
						</div>
						<div class="row">
							<label>
								<input type='checkbox' name='forced'>
								<span th:text="#{forced}"></span>
							</label>
						</div>
					</div>

					<div class="col-xl-5 flex-column">
						<h3>
							<span th:text="#{site_synch.microsoft_teams}">Microsoft Teams</span>
							<i class="fa fa-refresh" aria-hidden="true" href='#' role='button'
							onclick="doRefresh('teams-container', true)" tabindex="0"></i>
						</h3>
						<div class="card p-2 microsoft-block flex-column" style="height: 100%">
							<div>
								<input type="text" class="form-control microsoft-search"
									onkeyup="searchFilter(this)"
									data-list="teams-container"
									th:placeholder="|&#xF002; #{search}|">
								<div id="microsoft-error"></div>
							</div>
							<ul id="teams-container" class="list-unstyled" style="flex-grow: 1;">
								<li>
									<input id="new-team-checkbox" type='checkbox' name="selectedTeamIds" value="NEW" onchange="checkNewTeam(this.id)" />
									<label th:text="#{new}"></label>
									<input type='text' name="newTeamName" disabled />
								</li>
								<div id="teams-list">
									<th:block th:fragment="teams(teamsMap)">
										<th:block th:if="${teamsMap != null and teamsMap.size() > 0}">
											<li class="table-row" th:each="team : ${teamsMap}">
												<label>
													<input type='checkbox' name="selectedTeamIds" th:value="${team.key}"
														th:checked="${team.key} == ${selectedTeamId}"
														th:disabled="${siteSynchronizationId != null}" />
													<span class="title-row" th:text="${team.value.name}"></span>
												</label>
											</li>
										</th:block>
										<li th:if="${teamsMap == null or teamsMap.size() == 0}" th:text="#{site_synch.no_teams}"></li>
									</th:block>
								</div>
							</ul>
						</div>
					</div>
				</div>
				
				<div class="col-md-12 dates-container">
					<div id="dates-error"></div>
					
					<div class="date-element">
						<div th:text="#{sync_start_date}"></div>
						<input type="date" name="syncDateFrom" th:value="${syncDateFrom}" th:aria-label="#{index.start_date}" />
					</div>
					<div class="date-element">
						<div th:text="#{sync_end_date}"></div>
						<input type="date" name="syncDateTo" th:value="${syncDateTo}" th:aria-label="#{index.end_date}" />
					</div>
				</div>
				
				<div class="act col-md-12">
					<div class="col-md-12">
						<input class="active" type='submit' role="button" th:value="#{save}" />
						<input type='button' role="button" th:value="#{cancel}"
							th:onclick="'window.location.href = \'' +@{/index}+ '\''" />
					</div>
				</div>
			</form>
		</div>
		<script th:inline="javascript">

			(function () {
				document.querySelectorAll('.my-info-class').forEach((item) => {
					new bootstrap.Popover(item);
				});

				const form = document.querySelector('#siteSynchForm');

				form.addEventListener('keypress', handleButtonClick);
				form.addEventListener('keypress', function(e) {
					if (e.keyCode === 13) {
						e.preventDefault();
					}
				});

				doRefresh('teams-container', false);
			})();

			async function doRefresh(id, forced) {
				var teamsContainer = document.getElementById(id);
				
				var teamsList = document.getElementById('teams-list');
				if(teamsList){
					teamsList.innerHTML = '';
					teamsList.classList.add('hidden');
				}

				var spinner = setLoading(teamsContainer);

				let baseURL = "[(@{/refreshTeams})]";
				let url = baseURL + ((forced) ? '?forced=true' : '');
				let response = await fetch(url, {
						method: 'GET',
						headers: {
								'Accept': 'application/json',
						},
				});
				
				if(!response.ok){
					let data = await response.json();
					if (data.status == false) {
						let errorMicrosoftDiv = createError(teamsContainer);
						errorMicrosoftDiv.innerHTML = data.error;
						spinner.remove();
					}
					return;
				}
				
				let data = await response.text();

				spinner.remove();

				if(teamsList){
					teamsList.innerHTML = data;
					teamsList.classList.remove('hidden');
				}
			};

			async function filterSites(clear) {
				const siteSearch = document.getElementById("site-search");

				var siteValue = document.querySelector('input[name="siteType"]:checked').value;
				const publishedCheckbox = document.querySelector('input[name="published"]');
				const sitePropertyInput = document.querySelector('input[name="siteProperty"]');

				if (clear) {
					const siteRadioButtons = document.querySelectorAll('input[name="siteType"]');
					siteRadioButtons[2].checked = true;
					siteValue = siteRadioButtons[2].value;

					publishedCheckbox.checked = false;

					sitePropertyInput.value = '';
				}

				let baseURL = "[(@{/fiterSites})]";

				siteSearch.value = '';

				var sitesList = document.getElementById("sites-list");
				var sitesListContainer = sitesList.parentElement;

				sitesList.innerHTML = '';
				sitesList.classList.add('hidden');
				var spinnerElement = setLoading(sitesListContainer);

				const response = await fetch(baseURL, {
					method: 'POST',
					headers: {
						'Content-Type': 'application/json'
					},
					body: JSON.stringify(
						{
							siteType: siteValue,
							published: publishedCheckbox.checked,
							siteProperty: sitePropertyInput.value
						})
				});
				let content = await response.text();
				sitesList.innerHTML = content;
				spinnerElement.remove();
				sitesList.classList.remove('hidden');
			}

			function checkNewTeam(id) {
				const newTeamCheckbox = document.getElementById(id);
				const newTeamText = document.getElementsByName('newTeamName')[0];
				if (newTeamCheckbox.checked) {
					newTeamText.disabled = false;
					newTeamText.style.borderColor = 'black';
					newTeamText.required = true;
				} else {
					newTeamText.disabled = true;
					newTeamText.style.borderColor = '#E3E4E5';
					newTeamText.required = false;
				}
			}

			var siteTimeoutId = null;
			var teamsTimeoutId = null;
			var datesTimeoutId = null;
			
			const onSubmitForm = (event) => {
				event.preventDefault();

				const formObject = event.currentTarget;
				const formElements = formObject.elements;

				Array.prototype.slice.call(formElements).forEach((element) => {
					const { type, required, dataset } = element;

					if (["submit", "reset", "button"].includes(type) || !required) return;

					const validationType = dataset.validation;
					const value = element.value?.trim();
					const valueToMatch = validationType === "passwordConfirm" ? formElements.password?.value?.trim() : null;
					const { isValid, message } = validations[validationType]({ value, valueToMatch });

					setInputControlClassName({ element, isValid, message });
				});
			};
			
			function validateForm(formElem) {
				const sakaiSelected = formElem.querySelector('input[name="selectedSiteIds"]:checked');
				if (!sakaiSelected) {
					if(siteTimeoutId != null){
						clearTimeout(siteTimeoutId);
					}
					let sakaiContainer = document.getElementById('sakai-error');
					let errorSakaiDiv = createError(sakaiContainer);
					errorSakaiDiv.innerHTML = '[(#{error.sakai_sites})]';
					siteTimeoutId = setTimeout(() => errorSakaiDiv.remove(), 5000);
					return false;
				}

				const teamsSelected = formElem.querySelector('input[name="selectedTeamIds"]:checked');
				if (!teamsSelected) {
					if(teamsTimeoutId != null){
						clearTimeout(teamsTimeoutId);
					}
					let microsoftContainer = document.getElementById('microsoft-error');
					let errorMicrosoftDiv = createError(microsoftContainer);
					errorMicrosoftDiv.innerHTML = '[(#{error.microsoft_teams})]';
					teamsTimeoutId = setTimeout(() => errorMicrosoftDiv.remove(), 5000);
					return false;
				}
				
				const syncDateFrom = formElem.elements['syncDateFrom'].value;
				const syncDateTo = formElem.elements['syncDateTo'].value;
				if(!syncDateFrom || !syncDateTo || new Date(syncDateTo).getTime() < new Date(syncDateFrom).getTime() ){
					if(datesTimeoutId != null){
						clearTimeout(datesTimeoutId);
					}
					let container = document.getElementById('dates-error');
					let errorDatesDiv = createError(container);
					errorDatesDiv.innerHTML = (!syncDateFrom || !syncDateTo) ? '[(#{error.dates})]' : '[(#{error.dates_order})]';
					datesTimeoutId = setTimeout(() => errorDatesDiv.remove(), 5000);
					return false;
				}

				return true;
			}
			
			document.getElementById('siteSynchForm').onsubmit = function() {
				return validateForm(this);
			};
		</script>
	</div>
</body>

</html>
